package com.thiscc.sum.logic;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;
import com.thiscc.sum.common.MongoDBManager;
import com.thiscc.sum.constance.TableName;
import com.thiscc.sum.dao.CommonDao;
import com.thiscc.sum.dao.impl.CommonDaoImpl;
import com.thiscc.sum.utils.DBObjectUtils;
import com.thiscc.sum.utils.DateUtils;
import com.thiscc.sum.utils.JSONUtils;
import com.thiscc.sum.utils.ReduceCountUtils;
import com.thiscc.sum.utils.RequestUtils;
import com.thiscc.sum.utils.ShareUtils;
import com.thiscc.sum.utils.StringUtils;
import com.thiscc.sum.utils.TableNameConstant;
import com.thiscc.sum.webservice.WebService;

/**
 * 分享总结的业务逻辑操作类
 * @author DK
 * @createTime 2014.12.15
 *
 */
@Component
public class ShareLogic {

    //数据库操作对象
    private MongoDBManager db = MongoDBManager.getInstance();
    /**
     * 数据库操作类
     */
    @Autowired
    CommonDao commonDao = new CommonDaoImpl();

    @Autowired
    SumLogic sumLogic;

    public static Log log = LogFactory.getLog(ShareLogic.class);

    /*-------------------------------------------------------------------------------------------*/

    /**
     * 获得某篇总结的所有分享信息
     * @param request
     * @return
     * @author DK
     */
    public String getShare(HttpServletRequest request) {

        int i_pageCount = 0;
        int i_pageno = 0;

        //获取分页查询的数据
        String s_perPageCount = RequestUtils.getString(request, "perPageCount");//显示多少条
        String s_pageNo = RequestUtils.getString(request, "pageNo");//第几页

        if (StringUtils.isNotBlank(s_perPageCount) && StringUtils.isNotBlank(s_pageNo)) {

            i_pageCount = StringUtils.stringToInt(s_perPageCount);
            i_pageno = StringUtils.stringToInt(s_pageNo);
        }

        //String s_ccno = RequestUtils.(request, "ccno");//被分享人的ccno
        String s_ccno = request.getSession().getAttribute("uuid").toString();
        String s_id = RequestUtils.getString(request, "oid");//总结的唯一id

        DBObject DBO_condition = new BasicDBObject();
        DBO_condition.put("from", s_ccno);
        DBO_condition.put("oid", s_id);
        //        DBO_condition.put("oid", new ObjectId(s_id));

        //按时间排序
        DBObject DBO_order = new BasicDBObject("stime", -1);

        //数据库操作
        List<DBObject> l_dataArray = commonDao.searchLessCommon(TableNameConstant.T_SUMMARIZE_SHARE, DBO_condition, i_pageno, i_pageCount, DBO_order);

        JSONArray JSY_resultArray = new JSONArray();
        for (int i = 0; i < l_dataArray.size(); i++) {

            DBObject DBO_data = l_dataArray.get(i);

            String stime = DateUtils.dateToString(DBObjectUtils.getDate(DBO_data, "stime"), DateUtils.DATE_FORMAT_SS);
            String ztime = DateUtils.dateToString(DBObjectUtils.getDate(DBO_data, "ztime"), DateUtils.DATE_FORMAT_SS);

            DBO_data.put("stime", stime);
            DBO_data.put("ztime", ztime);

            List<DBObject> l_list = DBObjectUtils.getList(DBO_data, "address");
            JSONArray array = new JSONArray();

            for (int j = 0; j < l_list.size(); j++) {

                DBObject DBO_addressBean = l_list.get(j);
                String s_time = DateUtils.dateToString(DBObjectUtils.getDate(DBO_addressBean, "time"), DateUtils.DATE_FORMAT_SS);
                DBO_addressBean.put("time", s_time);
                array.add(DBO_addressBean);
            }

            DBO_data.put("address", array);
            JSY_resultArray.add(DBO_data);
        }

        return JSY_resultArray.toString();
    }

    /*-------------------------------------------------------------------------------------------*/

    /**
     * 分享我的总结
     * @param shareData 被分享总结的内容和数据
     * @param companyno 公司编码
     * @param uuidData 被选定人的json
     * @param groupidData 部门id和name
     * @return String类型 1成功  2 失败
     * @author DK
     */
    public String shareMarize(HttpServletRequest request) {

        //被分享的数据
        String shareData = RequestUtils.getString(request, "shareDate");

        //公司编号
        String companyno = RequestUtils.getString(request, "companyno");

        //分享给个人
        String s_uuidData = RequestUtils.getString(request, "uuidData");

        //分享给部门
        String groupData = RequestUtils.getString(request, "groupidData");

        //组装发送人的地址，用map保存，去掉重复的人   键为分享给人的uuid，值为分享给人的数据，
        Map<String, DBObject> shareToMap = new HashMap<String, DBObject>();

        DBObject address = null;

        JSONArray uuidData = new JSONArray();

        //分享给个人
        if (StringUtils.isNotBlank(s_uuidData)) {

            //被选定的人的json
            uuidData = JSONArray.fromObject(s_uuidData);

            String[] sharedAry = null;
            String s_uuid = null;

            for (int i = 0; i < uuidData.size(); i++) {

                address = new BasicDBObject();

                s_uuid = uuidData.getString(i);
                address.put("type", "0");//分享给个人为"0" ，分享给部门，为部门uuid

                sharedAry = s_uuid.split("\\*");
                address.put("uuid", sharedAry[0]);
                address.put("name", sharedAry[1]);

                address.put("time", new Date());
                address.put("state", "0");//是否已读，"0":未读 "1":已读

                shareToMap.put(sharedAry[0], address);
            }
        }

        //解析获得部门人员
        JSONArray JSY_dept = new JSONArray();
        JSONObject JSO_dept = new JSONObject();

        if (StringUtils.isNotBlank(groupData)) {

            //解析获得部门人员
            JSONArray groupArray = JSONArray.fromObject(groupData);
            String S_groupData = null;
            String[] S_frameArr = null;
            JSONArray framePeople = null;

            JSONObject JSO_frame = null;

            //循环部门
            for (int i = 0; i < groupArray.size(); i++) {

                S_groupData = groupArray.getString(i);

                S_frameArr = S_groupData.split("\\*");
                String S_frameId = S_frameArr[0];
                String S_frameName = S_frameArr[1];

                //获得部门信息
                JSO_dept.put("frameuuid", S_frameId);
                JSO_dept.put("name", S_frameName);

                //获得部门人员的信息
                framePeople = this.getUUIDByframe(companyno, S_frameId);

                //循环部门下的人
                for (int j = 0; j < framePeople.size(); j++) {

                    JSO_frame = framePeople.getJSONObject(j);

                    address = new BasicDBObject();

                    address.put("type", S_frameId);//部门编号
                    address.put("uuid", JSONUtils.getString(JSO_frame, "uuid"));//部门中的人员信息
                    address.put("name", JSONUtils.getString(JSO_frame, "name"));
                    address.put("time", new Date());
                    address.put("state", "0");

                    shareToMap.put(JSONUtils.getString(JSO_frame, "uuid"), address);
                }

                //部门信息
                JSY_dept.add(JSO_dept);
            }
        }

        JSONObject shareJson = JSONObject.fromObject(shareData);

        //获得分享人的名字、uuid
        String S_name = (request.getSession().getAttribute("realname")).toString();
        String S_uuid = JSONUtils.getString(shareJson, "uuid");

        if (StringUtils.isBlank(S_uuid) || "null".equals(S_uuid)) {

            S_uuid = request.getSession().getAttribute("uuid").toString();
        }

        //解析需要分享的总结
        DBObject shareBean = new BasicDBObject();
        shareBean.put("uuid", S_uuid);
        shareBean.put("ccno", request.getSession().getAttribute("ccno"));
        shareBean.put("name", S_name);

        Set<String> keySet = shareToMap.keySet();
        List<DBObject> addressList = new ArrayList<DBObject>();

        for (String key : keySet) {

            //不能分享给自己
            if (S_uuid.equals(key)) {
                continue;
            }

            addressList.add(shareToMap.get(key));
        }

        //要发送的人
        shareBean.put("address", addressList);
        shareBean.put("dept", JSY_dept);
        shareBean.put("from", JSONUtils.getString(shareJson, "from"));
        shareBean.put("fromname", JSONUtils.getString(shareJson, "fname"));
        shareBean.put("content", JSONUtils.getJSONArray(shareJson, "content"));

        //判断type类型，翻译成中文
        int I_type = JSONUtils.getInt(shareJson, "type");

        //给总结附中文的值
        switch (I_type) {
            case 1:
                shareBean.put("type", "日总结");
                break;
            case 2:
                shareBean.put("type", "周总结");
                break;
            case 3:
                shareBean.put("type", "月总结");
                break;
            case 4:
                shareBean.put("type", "年总结");
                break;
            default:
                shareBean.put("type", "年终总结");
                break;
        }

        shareBean.put("oid", JSONUtils.getString(shareJson, "oid"));

        String ztime = DBObjectUtils.getString(shareJson, "ztime");
        Date zdate = DateUtils.stringToDate(ztime, DateUtils.DATE_FORMAT_STS);

        shareBean.put("ztime", zdate);
        shareBean.put("stime", new Date());

        //数据库操作
        boolean flag = commonDao.insertCommon(TableNameConstant.T_SUMMARIZE_SHARE, shareBean);

        //将是否分享状态改为 "1"
        DBObject DBO_condition = new BasicDBObject("oid", JSONUtils.getString(shareJson, "oid"));
        DBObject DBO_update = new BasicDBObject("share", "1");

        flag = commonDao.updateCommon(TableName.SUMMARIZE_CONTENT, DBO_condition, DBO_update);

        String s_ret = flag ? "1" : "2";
        return s_ret;
    }

    /*-------------------------------------------------------------------------------------------*/
    /**
     *  分享页面---分享我的条数
     * @param shareMePid //分享我的功能点的ID
     * @param meSharePid //我分享的功能点的ID
     * @author 易泉 2014-12-15 16:14:00 
     */
    public String shareCount(HttpServletRequest request) {

        //拿到登录人的uuid 
        String s_uuid = request.getSession().getAttribute("uuid").toString();

        //分享我的功能点的ID
        String s_shareMePid = RequestUtils.getString(request, "shareMePid");

        //我分享的功能点的ID
        String s_meSharePid = RequestUtils.getString(request, "meSharePid");

        //分享我的查询条件
        DBObject DBO_conditionBean1 = new BasicDBObject();
        DBO_conditionBean1.put("uuid", s_uuid);
        DBO_conditionBean1.put("pid", s_shareMePid);

        //返回特定的字段
        DBObject DBO_less = new BasicDBObject();
        DBO_less.put("count", 1);

        //调用方法  拿到分享我的条数
        DBObject DBO_shareMeCount = commonDao.searchLessCommonOne(TableName.T_WORK, DBO_conditionBean1, DBO_less);

        if (DBO_shareMeCount != null) {

            DBO_shareMeCount.removeField("_id");
        }

        //我分享的查询条件
        DBObject DBO_conditionBean2 = new BasicDBObject();
        DBO_conditionBean2.put("uuid", s_uuid);
        DBO_conditionBean2.put("pid", s_meSharePid);

        //调用方法  拿到我分享的条数
        DBObject DBO_meShareCount = commonDao.searchLessCommonOne(TableName.T_WORK, DBO_conditionBean2, DBO_less);

        if (DBO_meShareCount != null) {

            DBO_meShareCount.removeField("_id");
        }

        JSONObject JSY_obj = new JSONObject();

        if (DBO_shareMeCount != null) {

            JSY_obj.put("shareMeCount", DBO_shareMeCount);
        } else {

            JSY_obj.put("shareMeCount", 0);
        }

        if (DBO_meShareCount != null) {

            JSY_obj.put("meShareCount", DBO_meShareCount);
        } else {

            JSY_obj.put("meShareCount", 0);
        }

        return JSY_obj.toString();
    }

    /*-------------------------------------------------------------------------------------------*/
    /**
     *  分享页面的分享我查询
     * @param pageNo //当前页数
     * @param perPageCount //总记录数
     * @param shareMePid //分享我的功能点的ID
     * @param reduce
     * @author 易泉
     */
    public String shareMe(HttpServletRequest request) {

        //拿到登录人的uuid
        String s_uuid = request.getSession().getAttribute("uuid").toString();

        //分享我的功能点的ID  shareMePid
        String s_shareMePid = RequestUtils.getString(request, "shareMePid");

        int i_reduce = RequestUtils.getInt(request, "reduce");

        //当前页数
        int i_pageNo = RequestUtils.getInt(request, "pageNo");

        //总记录数
        int i_perPageCount = RequestUtils.getInt(request, "perPageCount");

        //查询条件
        DBObject DBO_conditionBean = new BasicDBObject();
        DBO_conditionBean.put("from", s_uuid);

        //排序条件
        DBObject DBO_orderBy = new BasicDBObject();
        DBO_orderBy.put("stime", -1);

        //调用方法  
        List<DBObject> l_shareList = commonDao.searchLessCommon(TableName.SUMMARIZE_SHARE, DBO_conditionBean, i_pageNo, i_perPageCount, DBO_orderBy);

        if (i_reduce > 0) {

            //调用减少功能消息条数
            ReduceCountUtils.reduceMsgCount(s_uuid, s_shareMePid, i_reduce);
        }

        //返回类型  
        String s_result = ShareUtils.getData(l_shareList);

        return s_result;
    }

    /*-------------------------------------------------------------------------------------------*/
    /**
     *  分享页面的我分享查询
     * @param uuid //用户uuid
     * @param pageNo //当前页数
     * @param perPageCount //总页数
     * @author 易泉
     */
    public String meShare(HttpServletRequest request) {

        //拿到登录人的uuid 
        String s_uuid = request.getSession().getAttribute("uuid").toString();

        //分享我的功能点的ID  shareMePid
        String s_meSharePid = RequestUtils.getString(request, "meSharePid");

        int i_reduce = RequestUtils.getInt(request, "reduce");

        //当前页数
        int i_pageNo = RequestUtils.getInt(request, "pageNo");

        //每页显示的总记录数
        int i_perPageCount = RequestUtils.getInt(request, "perPageCount");

        //查询条件
        DBObject DBO_condition = new BasicDBObject();
        DBO_condition.put("uuid", s_uuid);

        //排序条件
        DBObject DBO_orderBy = new BasicDBObject();
        DBO_orderBy.put("stime", -1);

        //调用方法  
        JSONObject jo_shareList = JSONObject.fromObject(commonDao.searchCommonPage(TableName.SUMMARIZE_SHARE, DBO_condition, DBO_orderBy, i_pageNo, i_perPageCount));
        
        if (i_reduce > 0) {
            //调用减少功能消息条数
            ReduceCountUtils.reduceMsgCount(s_uuid, s_meSharePid, i_reduce);
        }

        return jo_shareList.toString();
    }

    /*-------------------------------------------------------------------------------------------*/
    /**
     *  分享操作成功进入的接口
     * @param uuid //选中的多个人
     * @param companyno 公司编号
     * @param frameUUID 部门uuid
     * @param functionid=110519816015296 分享我的功能ID
     * @author 易泉 
     */
    public String shareSuccess(HttpServletRequest request, HttpServletResponse response) {

        //选中的多个人
        String s_uuid = RequestUtils.getString(request, "uuid");

        //公司编号
        String s_companyno = RequestUtils.getString(request, "companyno");

        //部门uuid
        String s_frameUUID = RequestUtils.getString(request, "frameuuid");

        //功能点ID
        String s_functionid = RequestUtils.getString(request, "functionid");

        //定义一个JSONArray 添加查询出来的UUID
        JSONArray JSY_uuid = new JSONArray();

        //拿到的是String类型  数据库是数据 要做转换
        JSONArray JSY_leaguer = JSONUtils.getJSONArray(s_uuid);

        //拿到数组第一个值
        String s_empno = null;
        //remark
        String remark = RequestUtils.getString(request, "remark");
        JSONObject JSY_obj1 = new JSONObject();

        for (int i = 0; i < JSY_leaguer.size(); i++) {

            //拿到数组第一个值
            String s_strDept = JSY_leaguer.getString(i);

            //字符串截取
            int i_length = s_strDept.indexOf("*");

            s_empno = s_strDept.substring(0, i_length);

            JSY_obj1.put("uuid", s_empno);
            JSY_uuid.add(s_empno);
        }

        JSONArray JSY_deptUidd = null; //调用方法通过部门UUID查询部门所有的人的UUID
        String s_deptno = null; //截取后的部门ID
        JSONObject JSY_obj = null; //去掉返回的name  只要UUID
        String s_DeptStr = null; //拿到数组第一个值
        JSONArray JSY_dept = null; //把界面传参的部门编号转成数组形式

        if (StringUtils.isNotBlank(s_companyno) && StringUtils.isNotBlank(s_frameUUID)) {

            JSY_dept = JSONUtils.getJSONArray(s_frameUUID);

            for (int i = 0, len = JSY_dept.size(); i < len; i++) {

                //拿到数组第一个值
                s_DeptStr = JSY_dept.getString(i);

                //字符串截取
                int i_length = s_DeptStr.indexOf("*");

                s_deptno = s_DeptStr.substring(0, i_length);

                //调用方法 通过部门ID 查询部门人
                JSY_deptUidd = this.getUUIDByframe(s_companyno, s_deptno);

                for (int j = 0; j < JSY_deptUidd.size(); j++) {

                    JSY_obj = JSY_deptUidd.getJSONObject(j);
                    JSY_uuid.add(JSY_obj.getString("uuid"));
                }
            }
        }

        //WORK表操作
        //条件
        DBObject DBO_conditionDB = new BasicDBObject();

        List<DBObject> l_conditions = new ArrayList<DBObject>();
        JSONArray JSY_uuids = JSONArray.fromObject(JSY_uuid);

        DBObject DBO_condition = new BasicDBObject();

        for (int i = 0; i < JSY_uuids.size(); i++) {

            DBO_condition.put("uuid", JSY_uuids.get(i));
            DBO_condition.put("pid", s_functionid);

            l_conditions.add(DBO_condition);
        }

        DBO_conditionDB.put("$or", l_conditions);

        //修改数据
        DBObject DBO_updateDB = new BasicDBObject();
        DBO_updateDB.put("count", 1);

        db.updateInt(TableName.T_WORK, DBO_conditionDB, DBO_updateDB);

        DBO_updateDB = new BasicDBObject();
        DBO_updateDB.put("time", new Date());
        DBO_updateDB.put("remark", remark);

        boolean b_flag = db.update(TableName.T_WORK, DBO_conditionDB, DBO_updateDB);

        return b_flag ? "1" : "2";
    }

    /*-------------------------------------------------------------------------------------------*/

    /**
     * 根据公司编号、部门uuid递归查询，获取该部门下所有人的uuid，包括部门下的子部门
     * @param companyno 公司编号
     * @param frameUUID 部门uuid
     * @return
     * @author helios
     */
    private JSONArray getUUIDByframe(String companyno, String frameUUID) {

        WebService ws = new WebService();

        ws.setURL("/businessplat/services/CcAndroidService");
        ws.setMethodName("getCompanyCCByFrame");
        ws.setProperty(new String[] { companyno, frameUUID });

        String s_result = ws.getString();
        JSONArray JSY_UUID = JSONUtils.getJSONArray(s_result);
        return JSY_UUID;
    }

    /**
     * 查询共享
     * @author helios
     * @param request
     * @return  操作成功"1"  失败"2"
     * @createtime 2015-1-13
     * @since 1.0
     */
    public List<DBObject> shareToAll(HttpServletRequest request) {

        //拿到登录人的ccno
        String s_ccno = request.getSession().getAttribute("uuid").toString();

        DBObject DBO_condition = new BasicDBObject("address.uuid", s_ccno);

        int i_pageNo = RequestUtils.getInt(request, "pageNo");
        int i_pageSize = RequestUtils.getInt(request, "pageSize");

        DBObject DBO_order = new BasicDBObject("stime", -1);

        Object Obj_data = commonDao.searchCommonPage(TableName.SUMMARIZE_SHARE, DBO_condition, DBO_order, i_pageNo, i_pageSize);

        JSONObject JSO_ret = JSONUtils.getJsonObject(Obj_data.toString());

        JSONArray JSY_data = JSONUtils.getJSONArray(JSO_ret, "data");
        List<DBObject> l_ret = new ArrayList<DBObject>();

        JSONObject JSO_bean = null;
        DBObject DBO_bean = null;

        Date d_stime = null;//分享总结时间
        Date d_ztime = null;//发送总结时间

        String s_stime = null;
        String s_ztime = null;

        for (int i = 0, len = JSY_data.size(); i < len; i++) {

            JSO_bean = JSY_data.getJSONObject(i);
            DBO_bean = DBObjectUtils.jsonToDbObject(JSO_bean);

            //移除部门、分享人集合
            DBO_bean.removeField("dept");
            DBO_bean.removeField("address");

            d_stime = DBObjectUtils.getDate(DBO_bean, "stime");
            d_ztime = DBObjectUtils.getDate(DBO_bean, "ztime");

            s_stime = DateUtils.dateToString(d_stime, DateUtils.DATE_FORMAT_SS);
            s_ztime = DateUtils.dateToString(d_ztime, DateUtils.DATE_FORMAT_SS);

            DBO_bean.put("stime", s_stime);
            DBO_bean.put("ztime", s_ztime);

            l_ret.add(DBO_bean);
        }

        if (l_ret.size() == 0) {

            l_ret.add(new BasicDBObject());
        }

        //在第一条数据中添加共享总数
        l_ret.get(0).put("total", JSONUtils.getInt(JSO_ret, "total"));

        return l_ret;
    }
}
